package cn.kennylee.codehub.feign.interceptor.caller.remote.interceptors;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.Ordered;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * feign请求日志拦截器，打印请求体和header
 * <p>Created on 2025/6/17.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
@Slf4j
public class FeignRequestLogInterceptor implements RequestInterceptor, Ordered {

    public static final int ORDER = 0;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (log.isInfoEnabled()) {
            log.info("[Feign远程请求地址]: {} {}", requestTemplate.url(), requestTemplate.method());
            log.info("[Feign远程请求体]: headers={}, body={}", JSONUtil.toJsonStr(requestTemplate.headers()), getRequestBodyStr(requestTemplate));
        }
    }

    @NotNull
    private static String getRequestBodyStr(RequestTemplate requestTemplate) {
        byte[] body = requestTemplate.body();
        if (Objects.isNull(body)) {
            return StrUtil.EMPTY;
        }
        return new String(body, StandardCharsets.UTF_8);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
